<?php

namespace app\common\controller;

use think\Config;
use think\Db;
use think\exception\HttpResponseException;
use think\Log;
use think\Request;
use think\Response;

/**
 * API控制器基类
 */
class ApiBase extends Api
{

    protected $page = 1;//默认页码
    protected $limit = 10;//默认每页数量
    protected $maxLimit = 500;//每页最大数量

    protected $debug_sql = false;

    public function _initialize()
    {
        parent::_initialize();
        if ($this->debug_sql !== false || $this->request->post('debug')) {
            $this->debug_sql = [];
            Db::listen(function ($sql, $time, $explain) {
                $this->debug_sql[] = $sql . '   [' . $time . 's]';
            });
        }
    }

    /**
     * @return array
     */
    public function getPaginate()
    {
        $page = $this->request->param('page/d', $this->page);
        $limit = min($this->request->param('limit/d', $this->limit), $this->maxLimit);
        return ['page' => $page, 'list_rows' => $limit];
    }

    /**
     * 输出调试sql
     */
    protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'time' => Request::instance()->server('REQUEST_TIME'),
            'data' => $data,
        ];

        if ($this->debug_sql !== false && Config::get('app_debug')) {
            $result['param'] = $this->request->param();
            $result['sqls'] = $this->debug_sql;
        }
        // 如果未设置类型则使用默认类型判断
        $type = $type ?: $this->responseType;

        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }
        $response = Response::create($result, $type, $code)->header($header);
        throw new HttpResponseException($response);
    }

    //记录异常trace
    public function errorTrace($logMsg, $e, $echoMsg = false)
    {
        $apiTrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
        Log::error($logMsg . ' [ ' . $apiTrace[0]['file'] . ':' . $apiTrace[0]['line'] . ' ] ');
        Log::error($e->getMessage() . "  {$e->getFile()} [ line {$e->getLine()} ]");
        Log::error(var_export($this->request->param(), true));
        if ($echoMsg) {
            $this->error($logMsg);
        } else {
            $this->error('系统繁忙');
        }
    }

    protected function checkRequestParam($class, $param = [], $sence = '')
    {
        if (empty($param)) {
            $param = $this->request->param();
        }
        if (empty($sence)) {
            $sence = $this->request->action(true);
        }
        $validate = $this->validate($param, $class . '.' . $sence);
        if ($validate !== true) {
            $this->error($validate);
        }
    }

}
